package com.panwenliang.rememberwords.ui.register

import android.os.Bundle
import android.util.Log
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.core.widget.addTextChangedListener
import com.google.firebase.auth.FirebaseAuth
import com.panwenliang.rememberwords.R
import kotlinx.android.synthetic.main.activity_register.*


class RegisterActivity : AppCompatActivity() {

    private val TAG = "RegisterActivity"

    private lateinit var auth: FirebaseAuth

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_register)

        // [START initialize_auth]
        // Initialize Firebase Auth
        auth = FirebaseAuth.getInstance()
        // [END initialize_auth]

        etEmail.addTextChangedListener {
            when {
                !android.util.Patterns.EMAIL_ADDRESS.matcher(etEmail.text.toString()).matches() -> {
                    // Set error text
                    textInputLayoutEmail.error = "please input a valid email address"
                }
                else -> {
                    // Clear error text
                    textInputLayoutEmail.error = null
                }
            }
        }

        etPassword.addTextChangedListener {
            when {
                etPassword.length() < 6 -> {
                    // Set error text
                    textInputLayoutPassword.error = "please input password (6)"
                }
                else -> {
                    // Clear error text
                    textInputLayoutPassword.error = null
                }
            }
        }

        buttonRegister.setOnClickListener {
            auth.createUserWithEmailAndPassword(etEmail.text.toString(), etPassword.text.toString())
                .addOnCompleteListener(this) { task ->
                    if (task.isSuccessful) {
                        // Sign in success, update UI with the signed-in user's information
                        Log.d(TAG, "createUserWithEmail:success")
                        val user = auth.currentUser
//                    updateUI(user)
                    } else {
                        // If sign in fails, display a message to the user.
                        Log.w(TAG, "createUserWithEmail:failure", task.exception)
                        Toast.makeText(baseContext, "Authentication failed.",
                            Toast.LENGTH_SHORT).show()
//                    updateUI(null)
                    }

                    // ...
                }
        }
    }
}